//
//  SubmitSerOrderViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/28.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "NormalNaviView.h"

#import "SubmitSerOrderModel.h"

#import "OrderPayTypeCell.h"
#import "OrderPackageCell.h"
#import "SubmitOrderMarkCell.h"
#import "SubmitOrderItemShowCell.h"
#import "SubmitOrderItemActionCell.h"
#import "SubmitOrderQuanYiCell.h"

#import "SubmitOrderBottomView.h"
#import "SubmitOrderContactInfoView.h"

#import "SubmitOrderSectionHeader.h"
#import "SubmitOrderSectionFooter.h"

#import "CouponUseCollectViewController.h"
#import "SelPayMethodViewController.h"
#import "ScheduleInquiryViewController.h"
#import "SubmitSerOrderViewController.h"

@interface SubmitSerOrderViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NormalNaviView *naviView;

@property (nonatomic, strong) SubmitOrderContactInfoView *contactView;

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) SubmitOrderBottomView *bottomView;

@property (nonatomic, strong) SubmitSerOrderModel *submitModel;


@property (nonatomic, strong) NSMutableArray <CommonCouponModel *>*sellerSysCoupon;

@property (nonatomic, strong) NSMutableArray <CommonCouponModel *>*platformSysCoupon;

//商品总额
@property (nonatomic, assign) double goodsTotal;

//尾款总额
@property (nonatomic, assign) double weikuanTotal;


@end

@implementation SubmitSerOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self request_submitInfoWithType:CouponUseType_none AndScoId:@""];
}

- (void)goBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)initView {

    self.packageType = OrderPackageType_normal;
    if ([self.model.sellerModel.classId isEqualToString:Store_Category_siyi] ||
        [self.model.sellerModel.classId isEqualToString:Store_Category_genzhuang] ||
        [self.model.sellerModel.classId isEqualToString:Store_Category_sheying] ||
        [self.model.sellerModel.classId isEqualToString:Store_Category_genzhuang]) {
        
        self.packageType = OrderPackageType_SDJG;
    } else {
        self.packageType = OrderPackageType_normal;
    }
    
    self.model.sellerGoodsModel.isAllPay = YES;

    self.submitModel.deposit = self.model.sellerGoodsModel.goodsDeposit;

    self.submitModel.payType = 3;
    self.submitModel.goodsType = 1;
    self.submitModel.totalAmount = self.model.sellerGoodsModel.goodsActivePrice;
    self.submitModel.sellerId = self.model.sellerGoodsModel.sellerId;
    self.submitModel.userId = [TTUserModel sharedObject].userId;
    self.submitModel.serviceTime = @"";
    
    self.submitModel.bySellerVoList = @[].mutableCopy;
    
    HandleProSerStoreModel *model = [[HandleProSerStoreModel alloc] init];
    model.sellerId = self.model.sellerGoodsModel.sellerId;
    model.sellerName = self.model.sellerGoodsModel.sellerName;

    HandleProSerModel *goodsModel = [[HandleProSerModel alloc] init];
    goodsModel.goodsNum = 1;
    goodsModel.goodsPrice = self.model.sellerGoodsModel.goodsActivePrice;
    goodsModel.goodsId = self.model.sellerGoodsModel.goodsId;
    model.byGoodsVoList = @[].mutableCopy;
    [model.byGoodsVoList addObject:goodsModel];
    
    [self.submitModel.bySellerVoList addObject:model];
    
    self.title = @"填写订单";
    
    self.view.backgroundColor = UIColorHex(0xf0f0f0);
    
    self.navigationController.navigationBarHidden = YES;
    #if RT_INTERACTIVE_PUSH
        self.rt_navigationController.rt_enableInteractivePush = YES;
    #endif

    self.view.backgroundColor = UIColorHex(0xf0f0f0);
    
    CAGradientLayer *layer = [CAGradientLayer layer];
    layer.startPoint = CGPointMake(0, 0);
    layer.endPoint = CGPointMake(0, 1);
    
    layer.colors = @[(__bridge id)[UIColorHex(0xff4242) colorWithAlphaComponent:1].CGColor, (__bridge id)[UIColorHex(0xf0f0f0) colorWithAlphaComponent:1].CGColor];
    
    layer.frame = CGRectMake(0, 0, TTScreenWidth, TTScreenWidth * 0.826);
    [self.view.layer insertSublayer:layer atIndex:0];
    

    [self.view addSubview:self.naviView];
    
    [self.naviView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(kStatusBarHeight);
        make.height.mas_equalTo(44);
    }];
    
    self.contactView = [[NSBundle mainBundle] loadNibNamed:@"SubmitOrderContactInfoView"owner:nil options:nil].firstObject;
    
    if (self.packageType == OrderPackageType_normal) {
        self.contactView.frame = CGRectMake(0, 0, TTScreenWidth, 115);//根据情况变化
        self.contactView.serControlHeight.constant = CGFLOAT_MIN;
    } else {
        self.contactView.frame = CGRectMake(0, 0, TTScreenWidth, 165);//根据情况变化
        self.contactView.serControlHeight.constant = 50;
    }

    self.tableview.tableHeaderView = self.contactView;
    self.contactView.autoresizingMask = UIViewAutoresizingNone;
    
    self.bottomView =  [[NSBundle mainBundle] loadNibNamed:@"SubmitOrderBottomView"owner:nil options:nil].firstObject;
    
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.tableview];

    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.height.mas_equalTo(Bottom_SafeHeight + 60);
    }];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(self.bottomView.mas_top);
        make.top.mas_equalTo(self.naviView.mas_bottom);
    }];
    
    [self calculateTotalPay];
    [self.tableview reloadData];
    [self initViewAction];
}

- (void)initViewAction {
    
    WEAKSELF
    self.contactView.SubmitOrderContactInfoBlock = ^(NSString * _Nonnull content, SubmitOrderContactInfoType type) {
        switch (type) {
            case SubmitOrderContactInfoType_name:{
                weakSelf.submitModel.name = content;
            } break;
            case SubmitOrderContactInfoType_phone:{
                weakSelf.submitModel.tel = content;
            } break;
            case SubmitOrderContactInfoType_sertime:{
                
                ScheduleInquiryViewController *vc = [[ScheduleInquiryViewController alloc] init];
//                vc.packageId = weakSelf.model.sellerGoodsModel.goodsId;
                vc.sellerId = weakSelf.model.sellerGoodsModel.sellerId;
                [weakSelf.navigationController pushViewController:vc animated:YES];
                
                vc.ScheduleInquiryResultBlock = ^(NSString * _Nonnull resultDateStr) {
                    weakSelf.submitModel.serviceTime = resultDateStr;
                    weakSelf.contactView.serviceTimeLab.text = resultDateStr;
                };

            } break;
            default:
                break;
        }
    };
    
    self.bottomView.SubmitOrderBottomViewBlock = ^{
                
        if (self.submitModel.name.length == 0) {
            [SVProgressHUD showErrorWithStatus:@"请输入姓名"];
            [SVProgressHUD dismissWithDelay:1];
            return;
        }
        
        if (self.submitModel.tel.length == 0) {
            [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
            [SVProgressHUD dismissWithDelay:1];
            return;
        }
        
        if (self.packageType == OrderPackageType_SDJG) {
            if (self.submitModel.serviceTime.length == 0) {
                [SVProgressHUD showErrorWithStatus:@"请选择服务时间"];
                [SVProgressHUD dismissWithDelay:1];
                return;
            }
        }
        
        [weakSelf request_submitOrder];
    };
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return self.dataArray.count;
    return 5;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    switch (section) {
        case SubmitSerOrderSectionType_info:{
            return 1;
        } break;
        case SubmitSerOrderSectionType_payType:{
            return 1;
        } break;
        case SubmitSerOrderSectionType_priceInfo:{
            return 6;
        } break;
        case SubmitSerOrderSectionType_orderMark:{
            return 1;
        } break;
        case SubmitSerOrderSectionType_quanyi:{
            return 1;
        } break;
            
        default:
            break;
    }
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case SubmitSerOrderSectionType_info:{
            return 130;
        } break;
        case SubmitSerOrderSectionType_payType:{
            
            if (self.model.sellerGoodsModel.goodsDeposit > 0) {
                return 90;
            } else {
                return CGFLOAT_MIN;
            }
            
        } break;
        case SubmitSerOrderSectionType_priceInfo:{
            
            BOOL isAllPay = self.model.sellerGoodsModel.isAllPay;
            switch (indexPath.row) {
                case SubmitPriceInfoCellType_packagePrice:{
                    return 40;
                } break;
                case SubmitPriceInfoCellType_dingjin:{
                    return isAllPay?CGFLOAT_MIN:40;
                } break;
                case SubmitPriceInfoCellType_weikuan:{
                    return isAllPay?CGFLOAT_MIN:40;
                } break;
                case SubmitPriceInfoCellType_coupon:{
                } break;
                case SubmitPriceInfoCellType_pingtaijintie:{
                } break;
                case SubmitPriceInfoCellType_totalPay:{
                } break;
                default:
                    break;
            }
            
            return 40;
        } break;
        case SubmitSerOrderSectionType_orderMark:{
            return 40;
        } break;
        case SubmitSerOrderSectionType_quanyi:{
            return 115;
        } break;
        default:
            break;
    }
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    switch (section) {
        case SubmitSerOrderSectionType_info:{
            return 15;
        } break;
        case SubmitSerOrderSectionType_payType:{
            return CGFLOAT_MIN;
        } break;
        case SubmitSerOrderSectionType_priceInfo:{
            return 15;
        } break;
        case SubmitSerOrderSectionType_orderMark:{
            return 15;
        } break;
        case SubmitSerOrderSectionType_quanyi:{
            return 15;
        } break;
        default:
            break;
    }
    return 15;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    switch (section) {
        case SubmitSerOrderSectionType_info:{
            return 15;
        } break;
        case SubmitSerOrderSectionType_payType:{
            return CGFLOAT_MIN;
        } break;
        case SubmitSerOrderSectionType_priceInfo:{
            return 15;
        } break;
        case SubmitSerOrderSectionType_orderMark:{
            return 15;
        } break;
        case SubmitSerOrderSectionType_quanyi:{
            return 15;
        } break;
        default:
            break;
    }
    return 15;
}

#pragma mark sectionheader
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    SubmitOrderSectionHeader *headView = [[NSBundle mainBundle] loadNibNamed:@"SubmitOrderSectionHeader"owner:nil options:nil].firstObject;
    return  headView;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    SubmitOrderSectionFooter *footerView  =  [[NSBundle mainBundle] loadNibNamed:@"SubmitOrderSectionFooter"owner:nil options:nil].firstObject;
    return  footerView;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WEAKSELF
    switch (indexPath.section) {
        case SubmitSerOrderSectionType_info:{
            
            OrderPackageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderPackageCellID"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            [cell fillCellWithModel:self.model];
            return cell;
            
        } break;
        case SubmitSerOrderSectionType_payType:{
            
            OrderPayTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderPayTypeCellID"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            [cell fillCellWithModel:self.model.sellerGoodsModel];

            cell.OrderPayTypeCellBlock = ^(BOOL isAllPay) {
              
                weakSelf.model.sellerGoodsModel.isAllPay = isAllPay;
                
                //改变提交的钱数
                if (isAllPay) {
                    weakSelf.submitModel.totalAmount = weakSelf.model.sellerGoodsModel.goodsActivePrice;
                    weakSelf.submitModel.payType = 3;
                } else {
                    weakSelf.submitModel.totalAmount = weakSelf.model.sellerGoodsModel.goodsDeposit;
                    weakSelf.submitModel.payType = 1;
                }
                
                [weakSelf calculateTotalPay];
                [weakSelf.tableview reloadData];
            };
            
            return cell;
            
        } break;
        case SubmitSerOrderSectionType_priceInfo:{
            
            
            switch (indexPath.row) {
                case SubmitPriceInfoCellType_packagePrice:{
                    
                    SubmitOrderItemShowCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubmitOrderItemShowCellID"];
                    cell.selectionStyle =UITableViewCellSelectionStyleNone;
                    cell.itemSubTitle.hidden = YES;
                    cell.itemTitle.text = @"套餐价格";
                    cell.itemContent.text =[NSString stringWithFormat:@"¥%@",[Utilities changeDoubleToString:self.model.sellerGoodsModel.goodsActivePrice]];
                    return cell;
                    
                } break;
                case SubmitPriceInfoCellType_dingjin:{
                    
                    SubmitOrderItemShowCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubmitOrderItemShowCellID"];
                    cell.selectionStyle =UITableViewCellSelectionStyleNone;
                    cell.itemTitle.text = @"定金：待支付";
                    cell.itemSubTitle.hidden = NO;
                    cell.itemContent.text = [NSString stringWithFormat:@"¥%@",[Utilities changeDoubleToString:self.submitModel.deposit]];
                    return cell;
                } break;
                case SubmitPriceInfoCellType_weikuan:{
                    
                    SubmitOrderItemShowCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubmitOrderItemShowCellID"];
                    cell.selectionStyle =UITableViewCellSelectionStyleNone;
                    cell.itemTitle.text = @"尾款：未开始";
                    cell.itemSubTitle.hidden = YES;

                    cell.itemContent.text = [NSString stringWithFormat:@"¥%@",[Utilities changeDoubleToString:self.weikuanTotal]];
                    return cell;
                } break;
                case SubmitPriceInfoCellType_coupon:{
                    
                    SubmitOrderItemActionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubmitOrderItemActionCellID"];
                    cell.selectionStyle =UITableViewCellSelectionStyleNone;
                    cell.itemTitle.text = @"优惠券";
                    cell.itemSubTitle.hidden = YES;
                    if (self.submitModel.discountMcAmount > 0) {
                        cell.itemContent.textColor = UIColorHex(0xFF2442);
                        cell.itemContent.text =[NSString stringWithFormat:@"-¥%@",[Utilities changeDoubleToString:self.submitModel.discountMcAmount]];
                        cell.tagBtn.hidden = !self.submitModel.isRecMc;
                    } else {
                        cell.itemContent.textColor = UIColorHex(0xCDCDCD);
                        cell.itemContent.text = [NSString stringWithFormat:@"%ld张券可选",self.sellerSysCoupon.count];
                        cell.tagBtn.hidden = YES;
                    }
                    
                    return cell;
                    
                } break;
                case SubmitPriceInfoCellType_pingtaijintie:{
                    
                    SubmitOrderItemActionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubmitOrderItemActionCellID"];
                    cell.selectionStyle =UITableViewCellSelectionStyleNone;
                    cell.itemTitle.text = @"平台津贴";
                    if (self.submitModel.discountPcAmount > 0) {
                        cell.itemContent.textColor = UIColorHex(0xFF2442);
                        cell.itemContent.text =[NSString stringWithFormat:@"-¥%@",[Utilities changeDoubleToString:self.submitModel.discountPcAmount]];
                        cell.tagBtn.hidden = !self.submitModel.isRecPc;
                    } else {
                        cell.itemContent.textColor = UIColorHex(0xCDCDCD);
                        cell.itemContent.text = [NSString stringWithFormat:@"%ld张券可选",self.platformSysCoupon.count];
                        cell.tagBtn.hidden = YES;
                    }
                    
                    return cell;
                    
                } break;
                case SubmitPriceInfoCellType_totalPay:{
                    
                    SubmitOrderItemShowCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubmitOrderItemShowCellID"];
                    cell.selectionStyle =UITableViewCellSelectionStyleNone;
                    cell.itemSubTitle.hidden = YES;
                    cell.itemTitle.text = @"实付金额";
                    
                    cell.itemContent.text =[NSString stringWithFormat:@"¥%@",[Utilities changeDoubleToString:self.submitModel.totalAmount]];

                    return cell;
                    
                } break;
                default:
                    break;
            }
            
        } break;
        case SubmitSerOrderSectionType_orderMark:{
            
            SubmitOrderMarkCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubmitOrderMarkCellID"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            cell.orderMarkTF.text = self.submitModel.remark;
            
            cell.textFieldChangeBlock = ^(NSString * _Nonnull content) {
                weakSelf.submitModel.remark = content;
            };
            return cell;
            
        } break;
        case SubmitSerOrderSectionType_quanyi:{

            SubmitOrderQuanYiCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubmitOrderQuanYiCellID"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;

        } break;
        default:
            break;
    }
    
    OrderPackageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderPackageCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WEAKSELF
    switch (indexPath.section) {
        case SubmitSerOrderSectionType_info:{
        } break;
        case SubmitSerOrderSectionType_payType:{
        } break;
        case SubmitSerOrderSectionType_priceInfo:{
            switch (indexPath.row) {
                case SubmitPriceInfoCellType_packagePrice:{
                } break;
                case SubmitPriceInfoCellType_dingjin:{
                } break;
                case SubmitPriceInfoCellType_weikuan:{
                } break;
                case SubmitPriceInfoCellType_coupon:{

                    [weakSelf selectCouponWithDataArray:self.sellerSysCoupon Type:CouponUseType_store];
                } break;
                case SubmitPriceInfoCellType_pingtaijintie:{
                    
                    [weakSelf selectCouponWithDataArray:self.platformSysCoupon Type:CouponUseType_platform];
                } break;
                case SubmitPriceInfoCellType_totalPay:{
                } break;
                default:
                    break;
            }
        } break;
        case SubmitSerOrderSectionType_orderMark:{

        } break;
        default:
            break;
    }
}

- (void)selectCouponWithDataArray:(NSMutableArray <CommonCouponModel *>*)dateArray Type:(CouponUseType)type {
    
    if (dateArray.count == 0) {
        switch (type) {
            case CouponUseType_platform: {
                 [SVProgressHUD showErrorWithStatus:@"无可用平台津贴"];
                 [SVProgressHUD dismissWithDelay:1];
            } break;
            case CouponUseType_store: {
                 [SVProgressHUD showErrorWithStatus:@"无可用优惠券"];
                 [SVProgressHUD dismissWithDelay:1];
            } break;
            default:
                break;
        }
        return;
    }
    
    WEAKSELF
    CouponUseCollectViewController *pop = [[CouponUseCollectViewController alloc]initDefaultHeight:0.6*TTScreenHeight vc:self dataSource:dateArray.mutableCopy type:type];
    STPopupController *popVericodeController = [[STPopupController alloc] initWithRootViewController:pop];
    popVericodeController.style = STPopupStyleBottomSheet;
    [popVericodeController presentInViewController:self];
    pop.selectIndex = ^(NSInteger index, CouponUseType type) {
        
        switch (type) {
            case CouponUseType_store:{//选择了一个店铺优惠券
                
                if (index>=0 && index <weakSelf.sellerSysCoupon.count) {
                    weakSelf.submitModel.discountMcId = weakSelf.sellerSysCoupon[index].ucId;
                    weakSelf.submitModel.discountMcAmount = weakSelf.sellerSysCoupon[index].scoCut;
                    weakSelf.submitModel.isRecMc = weakSelf.sellerSysCoupon[index].isRec;
                } else {
                    weakSelf.submitModel.discountMcId = @"";
                    weakSelf.submitModel.discountMcAmount = 0;
                    weakSelf.submitModel.isRecMc = NO;
                }
                

                //修改券的选中以及刷新tableview
                [weakSelf refreshDataArray:weakSelf.sellerSysCoupon AndSelectIndex:index];
                
                [weakSelf request_submitInfoWithType:type AndScoId:weakSelf.submitModel.discountMcId];
                
            } break;
            case CouponUseType_platform:{//选择了一个商家优惠券
                
                if (index>=0 && index <weakSelf.platformSysCoupon.count) {
                    weakSelf.submitModel.discountPcId = weakSelf.platformSysCoupon[index].ucId;
                    weakSelf.submitModel.discountPcAmount = weakSelf.platformSysCoupon[index].scoCut;

                    if (weakSelf.platformSysCoupon[index].isRec) {
                        NSLog(@"1");
                    } else {
                        NSLog(@"0");
                    }
                    weakSelf.submitModel.isRecPc = weakSelf.platformSysCoupon[index].isRec;

                } else {
                    weakSelf.submitModel.discountPcId = @"";
                    weakSelf.submitModel.discountPcAmount = 0;
                    weakSelf.submitModel.isRecPc = NO;
                    
                    NSLog(@"");
                }
                //修改券的选中以及刷新tableview
                [weakSelf refreshDataArray:weakSelf.platformSysCoupon AndSelectIndex:index];
                
                [weakSelf request_submitInfoWithType:type AndScoId:weakSelf.submitModel.discountPcId];

            } break;
            default:
                break;
        }
        
        [weakSelf.tableview reloadData];
    };
}

- (void)refreshDataArray:(NSMutableArray <CommonCouponModel *>*)dataArray AndSelectIndex:(NSInteger)index {
    
    for (CommonCouponModel *model in dataArray) {
        model.isSel = NO;
    }
    
    if (index >=0 && index < dataArray.count) {
        dataArray[index].isSel = YES;
    }
    
    [self.tableview reloadData];
}

- (SubmitSerOrderModel *)submitModel {
    if (!_submitModel) {
        _submitModel = [[SubmitSerOrderModel alloc] init];
    }
    return _submitModel;
}

//商家优惠券
- (NSMutableArray<CommonCouponModel *> *)sellerSysCoupon {
    if (!_sellerSysCoupon) {
        _sellerSysCoupon = @[].mutableCopy;
    }
    return _sellerSysCoupon;
}

//平台津贴
- (NSMutableArray<CommonCouponModel *> *)platformSysCoupon {
    if (!_platformSysCoupon) {
        _platformSysCoupon = @[].mutableCopy;
    }
    return _platformSysCoupon;
}

- (NormalNaviView *)naviView {
    if (!_naviView) {
        _naviView = [[NSBundle mainBundle] loadNibNamed:@"NormalNaviView"owner:nil options:nil].firstObject;
        _naviView.backgroundColor = UIColor.clearColor;
        _naviView.titleLab.text = @"确认订单";
        _naviView.rightItem.hidden = YES;
        [_naviView.backBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    }
    return _naviView;
    
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  [UIColor clearColor];
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"OrderPackageCell" bundle:nil] forCellReuseIdentifier:@"OrderPackageCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"OrderPayTypeCell" bundle:nil] forCellReuseIdentifier:@"OrderPayTypeCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"SubmitOrderQuanYiCell" bundle:nil] forCellReuseIdentifier:@"SubmitOrderQuanYiCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"SubmitOrderMarkCell" bundle:nil] forCellReuseIdentifier:@"SubmitOrderMarkCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"SubmitOrderItemShowCell" bundle:nil] forCellReuseIdentifier:@"SubmitOrderItemShowCellID"];

        [_tableview registerNib:[UINib nibWithNibName:@"SubmitOrderItemActionCell" bundle:nil] forCellReuseIdentifier:@"SubmitOrderItemActionCellID"];

    }
    return _tableview;
}

//计算总价
- (void)calculateTotalPay {
    //算出商品总价
    self.goodsTotal = 0;
    self.weikuanTotal = 0;
    double total = 0;
    
    //商品原价不变
    self.goodsTotal = self.model.sellerGoodsModel.goodsActivePrice;

    //根据定金全款来付
    
    //1定金     3全款
    if (self.submitModel.payType == 1) {
        //计算尾款减去券的钱
        
        double wk = self.model.sellerGoodsModel.goodsActivePrice - self.model.sellerGoodsModel.goodsDeposit;
        double cut = self.submitModel.discountMcAmount + self.submitModel.discountPcAmount;

        if (wk - cut > 0) {
            self.weikuanTotal = wk - cut;
        } else {
            self.weikuanTotal = 0;
        }
        
        self.submitModel.totalAmount = self.model.sellerGoodsModel.goodsDeposit;

    } else if (self.submitModel.payType == 3){
        //计算总额减去券的钱
        total = self.model.sellerGoodsModel.goodsActivePrice;
        double cut = self.submitModel.discountMcAmount + self.submitModel.discountPcAmount;
    
        if (total - cut > 0) {
            self.submitModel.totalAmount = total - cut;
        } else {
            self.submitModel.totalAmount = 0;
        }

    }
    
    
    
//    double cut = self.submitModel.discountMcAmount + self.submitModel.discountPcAmount;
//
//    if (total - cut > 0) {
//        self.submitModel.totalAmount = total - cut;
//    } else {
//        self.submitModel.totalAmount = 0;
//    }

    
    //富文本
    
    double packageCommission = [BA_BusinessHelper shared].userProportion*0.01;
    double tax = [BA_BusinessHelper shared].taxPoint *0.01;
    
    NSString *doubleStr = [NSString stringWithFormat:@"%.2f",self.submitModel.totalAmount*packageCommission*(1-tax)];
    NSDecimalNumber *dn = [NSDecimalNumber decimalNumberWithString:doubleStr];
    
    NSString *totalPriceShow =[NSString stringWithFormat:@"¥%@",[Utilities changeDoubleToString:self.submitModel.totalAmount]];
    NSString *fanxianShow = [NSString stringWithFormat:@"(支付立返约¥%@)",dn.stringValue];
    
    if ([BA_BusinessHelper shared].userProportion == 0) {
        fanxianShow = @" ";
    }
    
    NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@%@",totalPriceShow,fanxianShow]];
     
    NSRange countRange = NSMakeRange(0, totalPriceShow.length-1);
    NSRange datRange = NSMakeRange(totalPriceShow.length,fanxianShow.length);

    // 设置字体大小
    [attribtStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:15] range:countRange];
    [attribtStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10] range:datRange];

     //赋值
    self.bottomView.totalMoneyLab.attributedText = attribtStr;
    
    
}

//请求提交订单数据，根据用券情况算出钱
- (void)request_submitInfoWithType:(CouponUseType)type AndScoId:(NSString *)scoId {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:[TTUserModel sharedObject].cityId forKey:@"scoCityId"];
    [dic setValue:[TTUserModel sharedObject].cityName forKey:@"cityName"];
    
    
    //商品数组
    NSMutableArray *goodsId = @[].mutableCopy;
    [goodsId addObject:self.model.sellerGoodsModel.goodsId];
    [dic setValue:goodsId forKey:@"goodsId"];
    
    //sku数组
    NSMutableArray *skuVo = @[].mutableCopy;
    NSDictionary *sku = @{}.mutableCopy;
    [sku setValue:@(self.model.sellerGoodsModel.goodsActivePrice) forKey:@"skuPrice"];
    [sku setValue:@"1" forKey:@"skuNum"];
    [skuVo addObject:sku];
    [dic setValue:skuVo forKey:@"skuVo"];

    [dic setValue:self.submitModel.sellerId forKey:@"sellerId"];
    [dic setValue:self.model.sellerModel.classId forKey:@"classsId"];

    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
        
    if (type != CouponUseType_none) {
        [dic setValue:@((CouponUseType)type) forKey:@"scoCouponType"];
        [dic setValue:scoId forKey:@"scoId"];
    }
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_SubmitEditOrder];

    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *sellerSysCoupon = [resultDic valueForKey:@"sellerSysCoupon"];
                NSArray *platformSysCoupon = [resultDic valueForKey:@"platformSysCoupon"];

                if (weakSelf.submitModel.name.length == 0) {
                    weakSelf.submitModel.name = [resultDic valueForKey:@"userName"];
                }
                
                if (weakSelf.submitModel.tel.length == 0) {
                    weakSelf.submitModel.tel = [resultDic valueForKey:@"userTel"];
                }

                if ([sellerSysCoupon isKindOfClass:[NSArray class]]) {
                    
                    if (sellerSysCoupon.count > 0) {

                        weakSelf.sellerSysCoupon = @[].mutableCopy;
                        for (int i = 0; i < sellerSysCoupon.count; i++) {
                            NSDictionary *sellerSysCouponDic = sellerSysCoupon[i];
                            CommonCouponModel *model = [CommonCouponModel modelWithDictionary:sellerSysCouponDic];
                            
                            if (model.couponUsa == 1) {
                                model.calSel = YES;
                            } else {
                                model.calSel = NO;
                            }
                            
                            [weakSelf.sellerSysCoupon addObject:model];
                        }
                    }
                }
                
                if ([platformSysCoupon isKindOfClass:[NSArray class]]) {
                    
                    if (platformSysCoupon.count > 0) {

                        weakSelf.platformSysCoupon = @[].mutableCopy;
                        for (int i = 0; i < platformSysCoupon.count; i++) {
                            NSDictionary *platformSysCouponDic = platformSysCoupon[i];
                            CommonCouponModel *model = [CommonCouponModel modelWithDictionary:platformSysCouponDic];
                            
                            if (model.couponUsa == 1) {
                                model.calSel = YES;
                            } else {
                                model.calSel = NO;
                            }
                            
                            [weakSelf.platformSysCoupon addObject:model];
                        }
                    }
                }
                
                weakSelf.contactView.nameTF.text = weakSelf.submitModel.name;
                weakSelf.contactView.phoneTF.text = weakSelf.submitModel.tel;
                
                if (type == CouponUseType_none) {
                    [weakSelf configBestCouponWith:resultDic];
                }

                [weakSelf calculateTotalPay];
                [weakSelf.tableview reloadData];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];

    }];
    
}

//获取最佳优惠券搭配
- (void)configBestCouponWith:(NSDictionary *)resultDic {
    
    NSDictionary* isBestSellerSysCoupon = [resultDic valueForKey:@"isBestSellerSysCoupon"];
    NSDictionary* isBestPlatformSysCoupon = [resultDic valueForKey:@"isBestPlatformSysCoupon"];
//
    CommonCouponModel *sellerCouponModel = [CommonCouponModel modelWithDictionary:isBestSellerSysCoupon];
    CommonCouponModel *sysCouponModel = [CommonCouponModel modelWithDictionary:isBestPlatformSysCoupon];
    
    if (sellerCouponModel.scoCut > 0) {
        self.submitModel.discountMcId = sellerCouponModel.ucId;
        self.submitModel.discountMcAmount = sellerCouponModel.scoCut;
        self.submitModel.isRecMc = YES;
    }

    if (sysCouponModel.scoCut > 0) {
        self.submitModel.discountPcId = sysCouponModel.ucId;
        self.submitModel.discountPcAmount = sysCouponModel.scoCut;
        self.submitModel.isRecPc = YES;
    }
    
    for (CommonCouponModel *model in self.sellerSysCoupon) {
        
        if ([model.ucId isEqualToString:sellerCouponModel.ucId]) {
            NSInteger index = [self.sellerSysCoupon indexOfObject:model];
            self.sellerSysCoupon[index].isRec = YES;
            [self refreshDataArray:self.sellerSysCoupon AndSelectIndex:index];
        }
    }
    
    for (CommonCouponModel *model in self.platformSysCoupon) {
        if ([model.ucId isEqualToString:sysCouponModel.ucId]) {
            NSInteger index = [self.platformSysCoupon indexOfObject:model];
            self.platformSysCoupon[index].isRec = YES;
            [self refreshDataArray:self.platformSysCoupon AndSelectIndex:index];
        }
    }
}

- (void)request_submitOrder {
            
    self.bottomView.submitBtn.userInteractionEnabled = NO;

    NSMutableDictionary *dic = @{}.mutableCopy;
    dic = [self.submitModel modelToJSONObject];
    
    NSMutableArray *bySellerVoList = @[].mutableCopy;

    for (int i = 0; i < self.submitModel.bySellerVoList.count; i++) {
        
        HandleProSerStoreModel *sellerModel = self.submitModel.bySellerVoList[i];
        NSMutableDictionary *sellerDic = [sellerModel modelToJSONObject];
        
        NSMutableArray *byGoodsVoList = @[].mutableCopy;
        for (int j = 0; j < self.submitModel.bySellerVoList[i].byGoodsVoList.count; j++) {
            HandleProSerModel *model = self.submitModel.bySellerVoList[i].byGoodsVoList[j];
            NSMutableDictionary *goodsDic = [model modelToJSONObject];
            [byGoodsVoList addObject:goodsDic];
        }
        [sellerDic setValue:byGoodsVoList forKey:@"byGoodsVoList"];
        [bySellerVoList addObject:sellerDic];
    }
    [dic setValue:bySellerVoList forKey:@"bySellerVoList"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_SubmitPackageOrder];

    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在提交订单"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        weakSelf.bottomView.submitBtn.userInteractionEnabled = YES;

        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                [[BA_BusinessHelper shared] clearBrowseData];

                NSDictionary *dic = [data valueForKey:@"data"];
                SelPayMethodModel *model = [SelPayMethodModel modelWithDictionary:dic];
                SelPayMethodViewController *vc = [[SelPayMethodViewController alloc] init];
                vc.entranceType = PayEntranceType_ser;
                vc.model = model;
                vc.goodsModel = weakSelf.model.sellerGoodsModel;
                [weakSelf.navigationController pushViewController:vc animated:YES];
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        weakSelf.bottomView.submitBtn.userInteractionEnabled = YES;
        [SVProgressHUD dismiss];

    }];
    
}

@end
